<script setup>
import { ref, defineProps } from 'vue'
import { ElMessage } from 'element-plus'
import userApi from '@/apis/user'

const props = defineProps({
  type: String,
  account: String,
  event: String,
})
const countDown = ref(0)

const send = async () => {
  if (countDown.value > 0) {
    ElMessage.error('请稍后获取验证码')
    return
  }

  if (props.type === 'email') {
    //检测是不是email
    const reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
    if (!reg.test(props.account)) {
      ElMessage.error('请输入正确的邮箱')
      return
    }
    await userApi.captcha.sendEms(props.account, props.event)
  } else if (props.type === 'mobile') {
    //检测是不是国内手机号
    const reg = /^1[3456789]\d{9}$/
    if (!reg.test(props.account)) {
      ElMessage.error('请输入正确的手机号')
      return
    }
    console.log('send', props.account, props.event)
    await userApi.captcha.sendSms(props.account, props.event)
    ElMessage.success('验证码已发送')
  } else {
    ElMessage.error('不支持的验证码类型')
  }

  countDown.value = 60
  const timer = setInterval(() => {
    countDown.value--
    if (countDown.value === 0) {
      clearInterval(timer)
    }
  }, 1000)
}
</script>

<template>
  <el-button
    :type="$attrs.buttonType"
    :class="$attrs.class"
    @click="send"
    :disabled="countDown > 0"
  >
    获取验证码{{ countDown ? `(${countDown})` : '' }}
  </el-button>
</template>
